package com.hgq.jssjyyxt.controller;

import com.hgq.jssjyyxt.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
@Slf4j
@RestController
@RequestMapping("upload")
public class UploadController {

    /**
     * 图片保存路径，自动从yml文件中获取数据
     * 示例： E:/images/
     */
    @Value("${file-save-path-win}")
    private String fileSavePathWin;

    @Value("${file-save-path-linux}")
    private String fileSavePathLinux;

    @PostMapping("img")
    public Result uploadFiles(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return Result.failure("上传失败，文件不能为空");
        }
        String os = System.getProperty("os.name").toLowerCase();
        String finalFileSavePath;
        if (os.contains("win")) {
            // 如果是Windows系统
            finalFileSavePath = fileSavePathWin;
        } else {
            // 如果是Linux系统
            finalFileSavePath = fileSavePathLinux;
        }
        String time = new Timestamp(System.currentTimeMillis()).toString().replace(" ", "-").replace(":", "-");
        String fileName = time + file.getOriginalFilename();
        File dir = new File(finalFileSavePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File newFile = new File(finalFileSavePath+fileName);
        try {
            file.transferTo(newFile);
            String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/images/" + fileName;
            log.info("图片上传，访问URL：" + url);
            return Result.success(url);
        } catch (IOException e) {
            return Result.failure("上传失败，后台错误");
        }
    }
}
